package com.sugon.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.DataFilter;
import com.sugon.dao.SysDeptDao;
import com.sugon.dao.SysRoleDao;
import com.sugon.dao.SysUserRoleDao;
import com.sugon.entity.SysDeptEntity;
import com.sugon.entity.SysRoleEntity;
import com.sugon.entity.SysUserEntity;
import com.sugon.modules.excel.IExcelHandler;
import com.sugon.modules.sys.consts.SysDeptConst;
import com.sugon.modules.sys.consts.SysRole;
import com.sugon.modules.sys.model.vo.PickerModel;
import com.sugon.service.SysDeptService;
import com.sugon.service.SysUserRoleService;
import com.sugon.service.SysUserService;
import com.sugon.utils.*;
import com.sugon.validator.Assert;
import com.sugon.validator.ValidatorUtils;
import com.sugon.validator.group.AddGroup;
import com.sugon.validator.group.UpdateGroup;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统用户
 *
 * @author lipengjun
 * @date 2017年11月18日 下午13:13:23
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysDeptDao sysDeptDao;
    @Resource
    private SysRoleDao roleDao;
    @Resource
    private SysUserRoleDao sysUserRoleDao;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private SysUserRoleService userRoleService;
    @Autowired
    @Qualifier("userExcelHandler")
    private IExcelHandler excelHandler;

    /**
     * 获取用户是否是特权人员
     * 所谓的特权用户指的是可以修改一些已经审批过的事项
     * 比如备件列表
     */
    @RequestMapping("/isPrivilege")
    @ResponseBody
    public R getUserRole() {
        String userId = ShiroUtils.getUserId();
        return R.ok().put("isPrivilege", sysUserService.isPrivilegeUser(userId) ? 1 : 0);
    }

    /**
     * 获取当前登录用的室主任列表
     */
    @GetMapping("/spareApproverList")
    public R spareApproverList() {
        return R.ok().put("approverList", sysUserService.listSpareApprover(ShiroUtils.getDeptSubCode()));
    }

    /**
     * 获取指定工号的审批人列表
     *
     * @param keyword 用户名或用户姓名
     * @return
     */
    @ApiOperation(value = "获取领导列表API")
    @ApiImplicitParam(name = "keyword", value = "用户名或用户姓名", required = true, dataType = "string", paramType = "query")
    @GetMapping("/loadLeaderList")
    public R loadLeaderList(@RequestParam String keyword) {
        List<PickerModel> leaderList = CollectionUtil.newArrayList();
        // 查询匹配用户
        Map<String, Object> param = MapUtil.newHashMap();
        param.put("keyword", keyword);
        param.put("leader", 1);
        List<SysUserEntity> userList = sysUserService.queryList(param);
        if (CollectionUtil.isNotEmpty(userList)) {
            leaderList.addAll(userList.stream().map(user -> new PickerModel(StrUtil.format("{}({})", user.getNickName(), user.getUserName()), user.getUserId())).collect(Collectors.toList()));
        }
        return R.ok().put("approverList", leaderList);
    }

    /**
     * 获取当前登录用户所在车间的指定角色的用户列表
     *
     * @param roleCode
     * @return
     */
    @GetMapping("/loadWorkshopRoleUserList")
    public R loadWorkshopRoleUserList(@RequestParam String roleCode) {
        List<PickerModel> leaderList = CollectionUtil.newArrayList();
        List<PickerModel> leaderList2 = CollectionUtil.newArrayList();
        // 校验角色是否存在
        List<SysRoleEntity> roleList = roleDao.listByRoleCode(roleCode);
        if (CollectionUtil.isEmpty(roleList)) {
            return R.error("角色不存在，请确认！");
        }
        List<SysUserEntity> userList = sysUserRoleDao.queryWorkshopRoleUser(ShiroUtils.getWorkshop(), roleList.get(0).getRoleId());
        if (CollectionUtil.isNotEmpty(userList)) {
            leaderList.addAll(userList.stream().map(user -> new PickerModel(StrUtil.format("{}({})", user.getNickName(), user.getUserName()), user.getUserId())).collect(Collectors.toList()));
        }
        // 简单处理，将自己放到首位，方便选择
        for (PickerModel pickerModel : leaderList) {
            if (ShiroUtils.getUserId().equals(pickerModel.getValue())) {
                leaderList2.add(0, pickerModel);
            } else {
                leaderList2.add(pickerModel);
            }
        }
        return R.ok().put("userList", leaderList2);
    }

    @ApiOperation(value = "获取备件需求计划审批人列表API")
    @GetMapping("/spNeedsPlanApproverList")
    public R spNeedsPlanApproverList() {
        /*
            获取的人员包括业务主管、技术室主任、车间领导、制造处备件专员
        */
        List<SysUserEntity> userList = CollectionUtil.newArrayList();
        Set<String> tem = CollectionUtil.newHashSet();
        // 当前车间的设备技术室主管、车间领导
        List<SysUserEntity> cjldList = userRoleService.queryDeptUserByRoleId(ShiroUtils.getWorkshop(), SysRole.CJSBJSSZG.getRoleId(), SysRole.CJLD.getRoleId());
        if (CollectionUtil.isNotEmpty(cjldList)) {
            for (SysUserEntity cjld : cjldList) {
                if (tem.add(cjld.getUserId())) {
                    userList.add(cjld);
                }
            }
        }
        // 制造处
        List<SysUserEntity> zzcList = userRoleService.queryDeptUserByRoleId(SysDeptConst.ZZC_CODE, SysRole.ZZCSBJSSZG.getRoleId(), SysRole.BJGLZY.getRoleId());
        if (CollectionUtil.isNotEmpty(zzcList)) {
            for (SysUserEntity zzc : zzcList) {
                if (tem.add(zzc.getUserId())) {
                    userList.add(zzc);
                }
            }
        }
        return R.ok().put("approverList", userList);
    }

    /**
     * 重置用户登录次数
     * 防止出现用户登录失败次数超过5次后，一小时内不能登录的问题
     */
    @RequestMapping("/resetLoginTimes/{username}")
    public R resetLoginTimes(@PathVariable("username") String username) {
        SysUserEntity sysUserEntity = sysUserService.queryByUserName(username);
        if (sysUserEntity == null) {
            return R.error("用户不存在！");
        }
        // 移除登录次数记录
        redisTemplate.delete(Constant.USER_LOGIN_ATTEMPT_TIME_PREFIX + username);
        return R.ok();
    }

    /**
     * 所有用户列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:user:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<SysUserEntity> userList = sysUserService.queryList(query);
        int total = sysUserService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    public R info() {
        return R.ok().put("user", ShiroUtils.getUserEntity());
    }

    /**
     * 修改登录用户密码
     */
    @RequestMapping("/password")
    public R password(@RequestParam String password, @RequestParam String newPassword) {
        Assert.isBlank(newPassword, "新密码不为能空");

        password = Base64.encode(password);

        newPassword = Base64.encode(newPassword);
        if (password.equals(newPassword)) {
            return R.error("密码不能与原密码相同");
        }

        //更新密码
        int count = sysUserService.updatePassword(ShiroUtils.getUserId(), password, newPassword);
        if (count == 0) {
            return R.error("原密码不正确");
        }

        //退出
        ShiroUtils.logout();

        return R.ok("密码修改成功");
    }

    /**
     * 用户信息
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") String userId) {
        SysUserEntity user = sysUserService.queryObject(userId);

        //获取用户所属的角色列表
        List<String> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        return R.ok().put("user", user);
    }

    /**
     * 保存用户
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:user:save")
    public R save(@RequestBody SysUserEntity user) {
        // 数据完整性校验
        ValidatorUtils.validateEntity(user, AddGroup.class);
        // 用户名查重
        SysUserEntity userInDB = sysUserService.queryByUserName(user.getUserName());
        if (userInDB != null) {
            return R.error("用户名已存在,请确认");
        }
        user.setCreateUser(ShiroUtils.getUserId());
        sysUserService.save(user);
        return R.ok();
    }

    /**
     * 修改用户
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);
        // 用户名查重
        SysUserEntity userInDB = sysUserService.queryByUserName(user.getUserName());
        if (userInDB == null) {
            return R.error("用户名已存在,请确认");
        }
        sysUserService.update(user);
        return R.ok();
    }

    /**
     * 删除用户
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody String[] userIds) {
        // 系统管理员不能删除
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }
        // 用户不能删除自己
        if (ArrayUtils.contains(userIds, ShiroUtils.getUserId())) {
            return R.error("当前用户不能删除");
        }
        sysUserService.deleteBatch(userIds);
        return R.ok();
    }

    /**
     * 组织用户树
     *
     * @return
     */
    @RequestMapping("/tree")
    //@RequiresPermissions("sys:user:tree")
    public R getUserTree() {
        Map<String, Object> map = new HashMap<>();
        //查询部门
        //如果不是超级管理员，则只能查询本部门及子部门数据
        if (!Constant.SUPER_ADMIN.equals(getUserId())) {
            map.put("deptFilter", sysDeptService.getSubDeptIdList(getDeptId()));
        }
        List<SysDeptEntity> deptList = sysDeptService.queryList(map);
        //查询用户信息
        //只有超级管理员，才能查看所有管理员列表
        Map<String, Object> params = new HashMap<>();
        if (!Constant.SUPER_ADMIN.equals(getUserId())) {
            params.put("createUser", getUserId());
        }
        params.put("order", "asc");
        //查询列表数据

        List<SysUserEntity> userList = sysUserService.queryList(params);

        for (int i = 0; i < userList.size(); i++) {
            SysDeptEntity sysDeptEntity = new SysDeptEntity();
            SysUserEntity userEntity = userList.get(i);
            sysDeptEntity.setName(userEntity.getUserName());//名称
            sysDeptEntity.setParentId(userEntity.getDeptId());
            sysDeptEntity.setDeptId(userEntity.getUserId());
            deptList.add(sysDeptEntity);
        }
        return R.ok().put("list", deptList);
    }


    /**
     * 组织部门树
     *
     * @return
     */
    @RequestMapping("/treeDept")
    //@RequiresPermissions("sys:user:tree")
    public R getUserTreeDept() {
        Map<String, Object> map = new HashMap<>();
        //查询部门
        //如果不是超级管理员，则只能查询本部门及子部门数据
        if (!Constant.SUPER_ADMIN.equals(getUserId())) {
            map.put("deptFilter", sysDeptService.getSubDeptIdList(getDeptId()));
        }
        List<SysDeptEntity> deptList = sysDeptService.queryList(map);
        return R.ok().put("list", deptList);
    }

    /**
     * 组织部门树-车间
     *
     * @return
     */
    @RequestMapping("/treeDeptByType/{deptType}")
    public R treeDeptByType(@PathVariable("deptType") String deptType, Integer level) {
        List<SysDeptEntity> deptList = sysDeptService.queryListByType(deptType, level);
        return R.ok().put("list", deptList);
    }

    /**
     * 新组织部门树-车间
     *
     * @return
     */
    @RequestMapping("/treeDeptByType2/{deptType}")
    public R treeDeptByType2(@PathVariable("deptType") String deptType) {
        List<SysDeptEntity> deptList = sysDeptService.queryListByType2(deptType);
        return R.ok().put("list", deptList);
    }

    @RequestMapping("/treeDeptBySCX")
    public R treeDeptBySCX() {
        List<SysDeptEntity> list = sysDeptService.treeDeptBySCX();
        return R.ok().put("list", list);
    }

    @RequestMapping("/loadLineList")
    public R loadLineList() {
        List<SysDeptEntity> list = new ArrayList<>();
        // 获取工厂和车间
        List<SysDeptEntity> tyList = sysDeptDao.queryListByTY();
        // 获取产线
        List<SysDeptEntity> lineList = sysDeptDao.queryListLTLevel(3);
        list.addAll(tyList);
        list.addAll(lineList);
        return R.ok().put("list", list);
    }

    /**
     * 罗列维修人员组织树
     * 包括设备技术室
     * 维修班组
     * 技术质量室
     * 模具维修班组
     *
     * @param params
     * @return
     */
    @DataFilter(deptAlias = "t2.DEPT_ID")
    @RequestMapping("/listPersonOrganTree")
    public R listPersonOrganTree(@RequestParam Map<String, Object> params) {
        List<SysDeptEntity> list = sysDeptService.listPersonOrganTree(params);
        return R.ok().put("list", list);
    }

    @RequestMapping("/treeDeptByDept")
    public R treeDeptByDept() {
        List<SysDeptEntity> list = sysDeptService.treeDeptBySCX();
        return R.ok().put("list", list);
    }

    @RequestMapping("/treeDeptBySCXLevel")
    public R treeDeptByDept(Integer level) {
        List<SysDeptEntity> list = (level != null) ? sysDeptService.treeDeptByLevel(level) : sysDeptService.treeDeptBySCX();
        return R.ok().put("list", list);
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {
        List<SysUserEntity> list = sysUserService.queryList(params);
        return R.ok().put("list", list);
    }

    /**
     * 查询指定角色的所用用户
     */
    @RequestMapping("/queryAllRoleUser")
    @ResponseBody
    public R queryAllRoleUser(@RequestParam String roleCode) {
        List<SysUserEntity> list = sysUserService.queryAllRoleUser(roleCode);
        return R.ok().put("list", list);
    }

    /**
     * 查询本部门下的人员
     */
    @RequestMapping("/treeDeptByParent")
    @ResponseBody
    public R treeDeptByParent(@RequestParam Map<String, Object> params) {
        params.put("deptId", ShiroUtils.getDeptId());
        params.put("deptType", Constant.DT_SBWXZ);
        List<SysUserEntity> list = sysUserService.treeDeptByParent(params);
        return R.ok().put("list", list);
    }

    @RequestMapping("/batchImport")
    @RequiresPermissions("sys:user:imports")
    @ResponseBody
    public R batchImport(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            return R.error("上传文件不能为空！");
        }
        int rows = excelHandler.importExcelFromStream(file.getInputStream());
        return R.ok("成功导入" + rows + "记录");
    }

}
